from socket import *
from select import select

class HttpServer:
    def __init__(self,host='0.0.0.0',port=8888,hdir='./project1'):
        self.__hdir = hdir
        self.__host = host
        self.__port = port
        self.__address = (self.__host,self.__port)
        self.sockfd = self.__create_socket()
        self.rlist = [self.sockfd]
        self.wlist = []
        self.xlist = []
    
    # 创建套接字
    def __create_socket(self):
        sockfd = socket(AF_INET, SOCK_STREAM)
        sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, True)
        sockfd.bind(self.__address)
        return sockfd
    
    # 启动服务
    def server_forever(self):
        self.sockfd.listen(9)
        print("[*] Listen port %d ...."%self.__port)
        while True:
            rs,ws,xs = select(self.rlist, self.wlist, self.xlist)
            for r in rs:
                if r is self.sockfd:
                    connfd,addr = self.sockfd.accept()
                    print("Connect from:",addr)
                    self.rlist.append(connfd)
                else:
                    self.handle(r)
            for w in ws:
                pass
            for x in xs:
                pass
        
    def handle(self,connfd):
        # 接收HTTP请求
        request = connfd.recv(40960)
        if not request:
            self.rlist.remove(connfd)
            connfd.close()
            return
        # 提取请求内容
        request_line = request.splitlines()[0]
        _info = request_line.decode().split(" ")[1]
        print(connfd.getpeername(),':',_info)

        if _info == '/' or _info[-5:] == '.html':
            self.get_html(connfd,_info)
        else:
            self.get_data(connfd)

    def get_html(self,connfd,_info):
        if _info == '/':
            filename = self.__hdir + 'index.html'
            print(filename)
        else:
            filename = self.__hdir + _info
        try:
            # fd = open(filename,encoding='gbk',errors='ignore')
            fd = open("C:\\Users\\Razer\\Desktop\\c_cplus\\JavaScript\\demo\\project01\\login.html",encoding='gbk',errors='ignore')
        except Exception:
            response = "HTTP/1.1 404 Not Found\r\n"
            response += "Content-Type:text/html\r\n"
            response += "\r\n"
            response += "<h1>Sorry .....</h1>"
        else:
            response = "HTTP/1.1 200 OK\r\n"
            response += 'Content-type:text/html\r\n'
            response += '\r\n'
            response += fd.read()
        finally:
            connfd.send(response.encode())
    def get_data(self,connfd):
        response = "HTTP/1.1 200 OK\r\n"
        response += 'Content-type:text/html\r\n'
        response += '\r\n'
        response += "<h1>Wating for httpserver 3.0</h1>"
        connfd.send(response.encode())

def main():
    HOST = '0.0.0.0'
    PORT = 8888 
    DIR = 'C:\\Users\\Razer\\Desktop\\c_cplus\\JavaScript\\demo\\project01\\'
    httpd=HttpServer(HOST,PORT,DIR)
    httpd.server_forever()

if __name__ == "__main__":
    main()       